package com.tianquan.miracle.beans;

import com.tianquan.miracle.aware.BeanClassLoaderAware;
import com.tianquan.miracle.aware.BeanFactoryAware;
import com.tianquan.miracle.aware.BeanNameAware;
import com.tianquan.miracle.core.BeanFactory;

/**
 * @Author: tianquan
 * @CreateTime: 2024-09-28  22:12
 * @Description: 默认bean工厂
 */
public class DefaultBeanFactory extends AbstractBeanRegister implements BeanFactory {

    @Override
    public Object getBean(String name) {
        return getSingletonBean(name);
    }

    @Override
    public <T> T getBean(Class<T> aClass) {
        return (T) getSingletonBean(aClass);
    }

    @Override
    public boolean containsBean(String name) {
        return containsKey(name);
    }

    @Override
    public boolean containsBean(Class<?> aClass) {
        return containsValue(aClass);
    }

    @Override
    public void invokeAwareMethods(Object bean, String name) {
        try {
            if (bean instanceof BeanFactoryAware beanFactoryAware) {
                beanFactoryAware.setBeanFactory(this);
            }
            if (bean instanceof BeanClassLoaderAware beanClassLoaderAware) {
                beanClassLoaderAware.setBeanClassLoader(Thread.currentThread().getContextClassLoader());
            }
            if (bean instanceof BeanNameAware beanNameAware) {
                beanNameAware.setBeanName(name);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}
